package com.study.mybatis.demo.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.study.mybatis.demo.model.StudentInfo;
import com.study.mybatis.demo.vo.StudentVo;

public class StudentDao {
	
	public static void main(String[] args) throws IOException {
		
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		//获得sessionFactory,sessionFactory用于管理mybatis session,而session是跟数据打交道的
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		//获得session
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Object obj = sqlSession.selectOne("demo.student.findById",1);//demo.student为mapping.xml中的命名空间
		System.out.println(obj);
		
		Map<String, Object> conditionMap = new HashMap<String, Object>();
		conditionMap.put("name", "r");
		List<StudentInfo> students = sqlSession.selectList("demo.student.findList",conditionMap);
		for(StudentInfo student : students){
			System.out.println(student);
		}
		System.out.println("=====================");
		conditionMap.put("classesName", "g");
		conditionMap.put("age", 10);
		List<StudentVo> studentvos  = sqlSession.selectList("demo.student.finds",conditionMap);
		for(StudentVo studentvo : studentvos){
			System.out.println(studentvo);
		}
		
		
		System.out.println("=====================");
		//一对多
		obj = sqlSession.selectList("demo.classes.findById",1);
		System.out.println(obj);
		
		StudentInfo info = new StudentInfo();
		info.setName("Cary");
		info.setSex('1');
		info.setAge(20);
		info.setAddr("American");
		info.setMemo("");
//		int result = sqlSession.insert("demo.student.insert", info);
//		System.out.println(result);
//		System.out.println(info.getId());
		sqlSession.commit();
		System.out.println(info.getId());
		sqlSession.close();
	}

}
